package com.main.messagenotificationmanagement.interfaces.facade;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.main.common.base.resp.RespBody;
import com.main.crossdomaineventmanagement.event.core.EventPublisher;
import com.main.crossdomaineventmanagement.event.model.EventMessage;
import com.main.messagenotificationmanagement.interfaces.dto.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("")
@Slf4j
public class MessageFacade {

    @Autowired
    @Qualifier("rocketMQEventPublisher")
    private EventPublisher eventPublisher;

    @PostMapping("/send")
    public RespBody<String> sendMessage(@RequestBody MessageDTO message) throws JsonProcessingException {
        log.info(message.toString());
        Map<String, Object> payload = new HashMap<>();
        payload.put("payload", message.getPayload());
        payload.put("type", message.getType());
        payload.put("userId", message.getUserId());
        payload.put("groupId", message.getGroupId());
        payload.put("category", message.getCategory());
        payload.put("routeKey", message.getRouteKey());
        String payloadJson = new ObjectMapper().writeValueAsString(payload);
        EventMessage event = new EventMessage("WEBSOCKET_MSG",   message.getCategory().name(), payloadJson);
        eventPublisher.publish(event);
        return RespBody.ok("发送成功");
    }

    @MessageMapping("/hello") // 定义客户端发送消息的目的地前缀
    @SendTo("/topic/system") // 定义消息发送的目标地址，用于广播消息到客户端
    public Object processHelloMessageFromClient(String message, @Header("category")String category, @Header("type") String type) throws Exception {
        Thread.sleep(1000); // 假装我们正在做一些处理工作
        System.out.println(message);
        System.out.println(category);
        return message; // 返回响应消息给客户端
    }
}